import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from models import Friends

class FriendsPage(webapp.RequestHandler):
  def get(self):
    friends_query = Friends.all().order('-date')
    friends = friends_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'friends': friends,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class AddFriend(webapp.RequestHandler):
  def post(self):
    friend = Friends()
    if users.get_current_user():
      friend.owner = users.get_current_user()
    friend.nickname = self.request.get('nickname')
    friend.emailaddress = self.request.get('emailaddress')
    friend.put()
    self.redirect('/')

application = webapp.WSGIApplication(
  [('/', FriendsPage),
  ('/add', AddFriend)],
  debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()